<template>
  <div :key="componentsKey">

    <van-tabs v-model="active" type="card" color="#1989fa">
      <van-tab>
        <template #title>详细报项</template>
        <div class="tab_panel_wrap">
          <!-- 报项列表 -->
          <ul>
            <li v-for="(item, index) in entryInfoList" :key="index" class="entry_item gl_mb_5">
              <div class="gl_mb_5">
                <span class="entry_name gl_mr_10">{{ item.name }}</span>
                <span class="entry_gender">{{ item.gender }}</span>
              </div>
              <div class="entry_info gl_mb_5 gl_clear">
                <div class="entry_left gl_fl">证件号:</div>
                <div class="entry_right">{{ item.idCardNumber }}</div>
              </div>
              <div v-if="gameInfo.isFinal" class="entry_info gl_mb_5 gl_clear">
                <div class="entry_left gl_fl">参报赛区:</div>
                <div class="entry_right">{{ item.subCompetitionName }}</div>
              </div>
              <div class="entry_info gl_clear">
                <div class="entry_left gl_fl">项目:</div>
                <div class="entry_right">
                  <div v-for="jtem in item.individualEvents" :key="jtem.id" class="gl_mb_5 gl_ellipsis">
                    <span>{{ jtem.eventCategoryName }} </span>
                    <span>{{ jtem.eventGroupName }}</span>
                    <span>{{ jtem.eventShortName }}</span>
                  </div>
                  <div v-for="jtem in item.teamEvents" :key="jtem.id" class="gl_mb_5 gl_ellipsis">
                    <span>{{ jtem.eventCategoryName }} </span>
                    <span>{{ jtem.eventGroupName }}</span>
                    <span>{{ jtem.eventShortName }}</span>
                    <span v-if="jtem.weightClassName"> ({{ jtem.weightClassName }})</span>
                    <span v-if="jtem.teamNo"> {{ jtem.teamNo }}组</span>
                  </div>
                </div>
              </div>
            </li>
          </ul>
          <div v-if="isShowGoEdit" class="go_edit_wrap">
            <van-button plain block color="#666" type="info" size="small" @click="goEditEntry">去修改</van-button>
          </div>
        </div>
      </van-tab>
      <van-tab v-if="!calcEntry.isFree">
        <template #title>费用明细</template>
        <div class="tab_panel_wrap">
          <div v-for="(item, index) in chargesFormat" :key="index">
            <!-- 普通费用 -->
            <div v-if="item.code !== 'Insurance' && item.code !== 'Foot'" class="charge_item">
              <div class="charge_top">
                <div class="gl_mb_5">
                  <span class="entry_type gl_mr_10">{{ item.name }}</span>
                  <span class="entry_unitprice">{{ item.name }} {{ formatMoney(item.unitAmount) }} 元</span>
                </div>
                <div class="entry_info gl_mb_5 gl_clear">
                  <div>{{ formatItemNames(item) }}</div>
                </div>
              </div>
              <div class="charge_subtotal gl_clear">
                <div class="gl_fr">
                  <div class="gl_mr_10 gl_fl">
                    <span v-if="subTotal[item.code].text">{{ subTotal[item.code].text }} {{ item.itemsCount }} {{ subTotal[item.code].unit }}</span>
                  </div>
                  <div class="gl_fl">合计：{{ formatMoney(item.categoryAmount) }}元</div>
                </div>
              </div>
            </div>
            <!-- 保险 -->
            <div v-if="item.code === 'Insurance'" class="charge_item">
              <div class="charge_top">
                <div class="gl_mb_5">
                  <span class="entry_type gl_mr_10">{{ item.name }}</span>
                  <span class="entry_unitprice">{{ item.name }} {{ formatMoney(item.unitAmount) }} 元/人</span>
                </div>
                <div class="entry_info gl_mb_5 gl_clear">
                  <div v-for="(jtem, jndex) in item.items" :key="index + jndex" class="gl_mb_10">
                    <div>{{ jtem.name }}</div>
                    <div class="insurance_checkbox">
                      <van-checkbox :value="jtem.hasInsurance" :disabled="!jtem.canChange" shape="square" icon-size="16px" @click="changeInsurance(jtem)">
                        是否购买保险
                      </van-checkbox>
                    </div>
                  </div>
                </div>
              </div>
              <div class="charge_subtotal gl_clear">
                <div class="gl_fr">
                  <div class="gl_mr_10 gl_fl">
                    <span v-if="subTotal[item.code].text">{{ subTotal[item.code].text }} {{ item.itemsCount }} {{ subTotal[item.code].unit }}</span>
                  </div>
                  <div class="gl_fl">合计：{{ formatMoney(item.categoryAmount) }}元</div>
                </div>
              </div>
            </div>
            <!-- 脚套 -->
            <div v-if="item.code === 'Foot'" class="charge_item">
              <div class="charge_top">
                <div class="gl_mb_5">
                  <span class="entry_type gl_mr_10">{{ item.name }}</span>
                  <span class="entry_unitprice">{{ item.name }} {{ formatMoney(item.unitAmount) }} 元/人</span>
                </div>
                <div class="entry_info gl_mb_5 gl_clear">
                  <div v-for="(jtem, jndex) in item.items" :key="index + jndex">
                    <div>{{ jtem.name }}</div>
                    <div class="insurance_checkbox gl_clear">
                      <div class="footcover_wrap gl_fl">
                        <van-checkbox :value="jtem.needFootCover" :disabled="!jtem.canChange" shape="square" icon-size="16px" @click="changeNeedFootCover(jtem)">
                          是否需要赛事方提供脚套
                        </van-checkbox>
                      </div>
                      <div class="gl_fr">
                        <div class="gl_fl" style="line-height: 26px">脚码：</div>
                        <div class="footsize_wrap gl_fl">
                          <input v-model.number="jtem.$footSize" class="footsize_input" type="number" @input="onchangeFootSize($event, jtem)" @blur="onBlurFootSize(jtem)">
                          <!-- <van-field v-model="jtem.$footSize" type="number" input-align="center" :maxlength="2" @blur="onBlurFootSize(jtem)" /> -->
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="charge_subtotal gl_clear">
                <div class="gl_fr">
                  <div class="gl_mr_10 gl_fl">
                    <span v-if="subTotal[item.code].text">{{ subTotal[item.code].text }} {{ item.itemsCount }} {{ subTotal[item.code].unit }}</span>
                  </div>
                  <div class="gl_fl">合计：{{ formatMoney(item.categoryAmount) }}元</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>

  </div>
</template>

<script>
import {
  api_PUT_EventsManagementEntryComRegisterInsuranceCompetitionRegisterId, // 14-设置是否收保险
  api_PUT_EventsManagementEntryComRegisterFootCompetitionRegisterId // 15-设置脚码
} from '@/extend/api/gameswaggerApi/app.js';

export default {
  props: {
    calcEntry: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    isShowGoEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      active: 0,
      number: 0,
      subTotal: {
        BigTeam: { text: '共:', unit: '人' },
        Foot: { text: '共:', unit: '人' },
        Entry: { text: '共:', unit: '人' },
        SimultaneousEntry: { text: '共:', unit: '人' },
        Deposit: { text: '共:', unit: '人' },
        Insurance: { text: '共:', unit: '人' },
        Custom: { text: '共:', unit: '人' }
      },
      changeFootLoading: false
    };
  },
  computed: {
    chargesFormat() {
      const _charges = this.calcEntry.charges || [];
      return _charges.map(item => {
        if (item.code === 'Foot') {
          for (let j = 0; j < item.items.length; j++) {
            const jtem = item.items[j];
            jtem.$footSize = jtem.footSize ? jtem.footSize : 0;
          }
        }
        return item;
      });
    },
    componentsKey() {
      const _charges = this.calcEntry.charges || [];
      return String(_charges.length) + Math.random();
    },
    entryInfoList() {
      const _charges = this.calcEntry.charges || [];
      let _returnCharges = [];
      if (_charges.length) {
        for (let i = 0; i < _charges.length; i++) {
          const item = _charges[i];
          if (item.code === 'Entry') {
            _returnCharges = item.items;
            break;
          }
        }
      }
      return _returnCharges;
    },
    isShowTeamEvents() {
      return this.entryType !== 'Personal';
    }
  },
  methods: {
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 处理姓名显示
    formatItemNames(item) {
      const _namesList = item.items.map(item => item.name);
      const _namesStr = _namesList.join('，');
      return _namesStr;
    },
    // 是否被忽略
    hasColumn (chargeCode, tableProp) {
      return this.columnMap[chargeCode][tableProp];
    },
    entryToEdit() {
      this.$emit('onEntryEdit');
    },
    reGetCharges() {
      this.$emit('onReGetCharges');
    },
    // 改变保险
    changeInsurance (item) {
      const vo = {
        hasInsurance: !item.hasInsurance
      };
      this.comRegisterInsuranceApi(item.id, vo);
    },
    // 改变保险API
    comRegisterInsuranceApi(id, vo) {
      api_PUT_EventsManagementEntryComRegisterInsuranceCompetitionRegisterId(id, vo)
        .then(
          res => {
            this.$toast.success(`保险修改成功`);
            this.reGetCharges();
          }
        )
        .catch(
          error => {
            this.$toast.fail(`保险修改失败 ${error.error.message}`);
          }
        );
    },
    // 是否需要赛事方提供脚套
    changeNeedFootCover (item) {
      if (!item.canChange) {
        return;
      }
      if (this.changeFootLoading === false) {
        if (typeof item.$footSize === 'number' && item.$footSize > 0) {
          const vo = {
            footSize: item.needFootCover ? 0 : item.$footSize
          };
          this.comRegisterFootApi(item.id, vo);
        } else {
          // 用户不想写脚码，根据产品需求调整为填入默认值1
          this.comRegisterFootApi(item.id, {
            footSize: 1
          });
          // this.$toast.fail(`请输入脚码数`);
        }
      }
    },
    onchangeFootSize (event, data) {
      data.$footSize = event.target.value.replace(/\-/g, '');
    },
    // 改变脚码
    onBlurFootSize (item) {
      console.log('onBlurFootSize -> item', JSON.parse(JSON.stringify(item)));
      const _footSize = Number(item.$footSize) || 0;
      if (_footSize !== item.footSize) {
        if (typeof _footSize === 'number') {
          const vo = {
            footSize: _footSize
          };
          this.comRegisterFootApi(item.id, vo);
        } else {
          this.$toast.fail(`请输入脚码数`);
          item.footSize = _footSize;
        }
      }
    },
    // 改变脚码
    comRegisterFootApi(id, vo) {
      this.changeFootLoading = true;
      api_PUT_EventsManagementEntryComRegisterFootCompetitionRegisterId(id, vo)
        .then(
          res => {
            this.$toast.fail(`修改成功`);
            this.reGetCharges();
            this.changeFootLoading = false;
          }
        )
        .catch(
          error => {
            this.$toast.fail(`修改失败 ${error.error.message}`);
            this.reGetCharges();
            this.changeFootLoading = false;
          }
        );
    },
    goEditEntry () {
      this.$emit('onGoEditEntry');
    }
  }
};
</script>

<style scoped>
.tab_panel_wrap {
  padding: 20px 0 40px;
}
.charge_item,
.entry_item {
  width: 100%;
  margin-bottom: 5px;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.10);
}
.charge_top {
  border-bottom: 1px solid #d4d4d4;
}
.entry_type,
.entry_name {
  font-size: 14px;
  text-align: left;
  font-weight: bold;
  color: #333;
  line-height: 20px;
}
.entry_type {
  display: inline-block;
  vertical-align: middle;
  min-width: 60px;
}
.entry_unitprice,
.entry_gender {
  font-size: 12px;
  color: #666666;
  line-height: 20px;
}
.entry_info {
  font-size: 12px;
  text-align: left;
  color: #666;
  line-height: 16px;
}
.charge_subtotal {
  padding-top: 8px;
  font-size: 12px;
  color: #666666;
  line-height: 16px;
}
.entry_left {
  width: 50px;
}
.entry_right {
  margin-left: 50px;
}

.insurance_checkbox {
  padding-bottom: 5px;
}
.insurance_checkbox:last-child {
  padding-bottom: 0;
}

.footcover_wrap {
  padding-top: 3px;
}
.footsize_wrap {
  display: inline-block;
  vertical-align: middle;
  width: 80px;
  overflow: hidden;
}
.footsize_wrap .van-cell {
  padding: 0;
}
.footsize_input {
  width: 100%;
  height: 26px;
  border: 1px solid #979797;
  border-radius: 5px;
}

.go_edit_wrap {
  padding: 16px 0;
}
</style>
